package com.skyline.user.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.skyline.base.controller.BaseController;
import com.skyline.common.util.AuthorityUtil;
import com.skyline.common.util.Constant;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.user.model.Fan;
import com.skyline.user.model.User;
import com.skyline.user.service.FanService;
import com.skyline.user.service.BasicUserService;
import com.skyline.user.type.IdolType;

/**
 * BasicUserAction 用户基本操作，NameSpace为"/" 功能包括: 1.登陆 2.退出 3.注册
 * 
 * @author Jairus Chan
 * @version 0.1, 11/30/10
 */

@Controller
public class BasicUserController extends BaseController {
	private static final Log LOGGER = LogFactory.getLog(BasicUserController.class);

	@Autowired
	private BasicUserService basicUserService;

	@Autowired
	private FanService fanService;

	/**
	 * 用户访问"/login.html"跳转到登陆界面
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(String requestFrom) {
		ModelAndView view = new ModelAndView(ViewPaths.USER_LOGIN);
		view.addObject("REQUEST_FROM", StringUtils.trimToEmpty(requestFrom));
		WebHelper.saveToken(null);
		return view;
	}

	/**
	 * 对用户输入的信息进行验证，施行登陆
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(String email, String password, String requestFrom) {
		String loginIp = WebHelper.initRequest(null).getRemoteAddr();
		User user = basicUserService.login(email, password, loginIp);
		WebHelper.initRequest(null).setAttribute("REQUEST_FROM", StringUtils.trimToEmpty(requestFrom));
		if (user != null) {
			List<Fan> idols = fanService.listIdols(user.getId(), IdolType.USER);
			AuthorityUtil.initalAuthorityMatrix(null, user.getId(), idols);
			WebHelper.setSessionAttribute(null, Constant.SESSION_USER, user);
			WebHelper.setSessionAttribute(null, Constant.SESSION_IDOLS, idols);
			LOGGER.debug("登录成功，目标地址：" + requestFrom);
			if (StringUtils.isEmpty(requestFrom)) {
				String url = buildRecirectPath(ViewPaths.WO_MYWO);
				return new ModelAndView(new RedirectView(url));
			} else {
				return new ModelAndView(new RedirectView(requestFrom));
			}
		} else {
			return new ModelAndView(ViewPaths.USER_LOGIN);
		}
	}

	/**
	 * 退出，结束session
	 */
	@RequestMapping("/logout")
	public ModelAndView logout() {
		WebHelper.invalidateSession(null);
		ModelAndView view = new ModelAndView(ViewPaths.USER_LOGIN);
		return view;
	}

	/**
	 * 请求注册，当用户输入“/regist.html”时，跳转到注册界面
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.GET)
	public ModelAndView regist() {
		ModelAndView view = new ModelAndView(ViewPaths.USER_REGIST);
		return view;
	}

	/**
	 * 执行注册
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public ModelAndView regist(String email, String password, String passwordConfirm, String certcode) {
		ModelAndView v = new ModelAndView();
		String ip = WebHelper.initRequest(null).getRemoteAddr();
		String certcodeInSession = (String) WebHelper.getSessionAttribute(null, Constant.SESSION_CERT_CODE);
		if (certcode == null || !certcode.equals(certcodeInSession)) {
			v.setViewName(ViewPaths.USER_REGIST);
			return v;
		}
		if (email == null) {
			v.setViewName(ViewPaths.USER_REGIST);
			return v;
		} else if (password == null || !password.equals(passwordConfirm)) {
			v.setViewName(ViewPaths.USER_REGIST);
			return v;
		}
		try {
			basicUserService.regist(email, password, ip);
			v.setViewName(ViewPaths.USER_LOGIN);
			return v;
		} catch (Exception e) {
			e.printStackTrace();
			v.setViewName(ViewPaths.USER_REGIST);
			v.addObject("email", email);
			return v;
		}
	}

	/**
	 * 这是一个Ajax请求，验证此用户是否已经存在
	 */
	@RequestMapping("/verifyuser/{email}")
	@ResponseBody
	public Boolean verifyUser(@PathVariable String email) {
		return basicUserService.isUserExist(email);
	}

	/**
	 * 这是一个Ajax请求，通过ajax登陆系统
	 */
	@RequestMapping("/ajaxlogin")
	@ResponseBody
	public boolean ajaxLogin(String email, String password) {
		String loginIp = WebHelper.initRequest(null).getRemoteAddr();
		User user = basicUserService.login(email, password, loginIp);
		WebHelper.saveToken(null);
		if (user != null) {
			List<Fan> idols = fanService.listIdols(user.getId(), IdolType.USER);
			AuthorityUtil.initalAuthorityMatrix(null, user.getId(), idols);
			WebHelper.setSessionAttribute(null, Constant.SESSION_USER, user);
			WebHelper.setSessionAttribute(null, Constant.SESSION_IDOLS, idols);
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping("/getlogineduser")
	@ResponseBody
	public User getLoginedUser() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			user = new User();
			user.setId(Long.valueOf(0));
			user.setNickname("游客");
			user.setPortrait("portrait");
		}
		// u.getPortrait()
		return user;
	}
}
